<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, ref, onMounted, computed } from 'vue'
import useSchema from './hooks/useSchema'
import { useCrudSchemas, AllSchemas, CrudSchema } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { TableDialog } from '@/components/Custom/Purchase'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getSupplierListApi } from '@/api/supplier'
import { getSelectListApi } from '@/api/operator'
import { FieldEnum } from '@/api/purchase/types'
import { getFieldEnumApi, redInkReversalApi } from '@/api/purchase'
import { getListApi } from '@/api/product'
import { getCategoryListApi } from '@/api/category'
import { getBrandListApi } from '@/api/brand'
import { TableColumn } from '@/components/Table'
import { BaseButton } from '@/components/Button'

defineOptions({
  name: 'PurchaseSave'
})

const { t } = useI18n()

const emit = defineEmits<{
  refreshData: []
}>()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Record<string, any>>,
    default: () => null
  },
  examine: {
    type: Boolean,
    default: () => false
  },
  detail: {
    type: Boolean,
    default: () => false
  }
})

const tableDialogStoreID = 'purchaseWrite'
const itemTitleName = 'cname'
const tableDialogSelectedLimit = 50
const red_ink_reversalDialogVisible = ref(false)
const is_show_red_ink_payments = ref(false)
const is_show_red_ink_receipt = ref(false)
const payments_data_list = ref(props.currentRow?.payments || [])
const purchase_receipt_details_list = ref(props.currentRow?.purchase_receipt_details || [])
const payments_columns = computed<TableColumn[]>(() => [
  {
    field: 'id',
    label: t('tableDemo.index'),
    align: 'center',
    headerAlign: 'center',
    width: 60
  },
  {
    field: 'payno',
    label: t('payment.payno'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'pay_amount',
    label: t('payment.pay_amount'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'currency',
    label: t('purchase.currency'),
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const currencyObj = purchaseFieldEnum.value.currency || {}
        const currencyList = Object.values(currencyObj) as Array<{ value: number; label: string }>
        const currencyItem = currencyList.find((item) => item.value === data.row.currency)
        return <span>{currencyItem?.label || ''}</span>
      }
    }
  },
  {
    field: 'payment_date',
    label: t('payment.payment_date'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'pay_type_value',
    label: t('payment.pay_type'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'payment_account_value',
    label: t('payment.payment_account'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'status_value',
    label: t('payment.status'),
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        if (data.row.redrushed == 1) {
          return data.row.status_value + '（已红冲）'
        } else {
          return data.row.status_value
        }
      }
    }
  },
  {
    field: 'unit',
    label: t('payment.hash'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'responsible_value',
    label: t('payment.owner'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    align: 'center',
    headerAlign: 'center',
    hidden: !is_show_red_ink_payments.value,
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.is_redrush == 0 && data.row.status == 30 && (
              <BaseButton size="small" type="danger" onClick={() => action(data.row, 1)}>
                {t('action.red_ink_reversal')}
              </BaseButton>
            )}
          </>
        )
      }
    }
  }
])

const purchase_receipt_details_columns = computed<TableColumn[]>(() => [
  {
    field: 'id',
    label: t('tableDemo.index'),
    align: 'center',
    headerAlign: 'center',
    width: 60
  },
  {
    field: 'cname',
    label: t('inventory.cname'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'code',
    label: t('product.code'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'warehouse_name',
    label: t('inventory.warehouse_name'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'is_futures',
    label: t('inventory.is_futures'),
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        let text = ''
        switch (data.row.is_futures) {
          case 0:
            text = t('inventory.is_futures_0')
            break
          case 1:
            text = t('inventory.is_futures_1')
            break
          case 2:
            text = t('inventory.is_futures_2')
            break
          default:
            text = ''
        }
        return <span>{text}</span>
      }
    }
  },
  {
    field: 'arrival_date',
    label: t('inventory.arrival_date'),
    align: 'center',
    headerAlign: 'center',
    hidden: ((data: any) => (data.row.is_futures === 0 ? true : false)) as any
  },
  {
    field: 'real_arrival_date',
    label: t('inventory.real_arrival_date'),
    align: 'center',
    headerAlign: 'center',
    hidden: ((data: any) => (data.row.is_futures === 0 ? true : false)) as any
  },
  {
    field: 'number',
    label: t('purchase.already_receipt_quantity'),
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.is_redrush == 0 && data.row.is_show_red_ink_receipt && (
              <BaseButton size="small" type="danger" onClick={() => action(data.row, 2)}>
                {t('action.red_ink_reversal')}
              </BaseButton>
            )}
          </>
        )
      }
    }
  }
])

const action = (row: any, type: number) => {
  red_ink_reversalDialogVisible.value = true
  red_ink_reversal_form.value.type = type
  if (type == 1) {
    red_ink_reversal_form.value.payments_id = row.id
    red_ink_reversal_form.value.amount = red_ink_reversal_form.value.max_amount
  } else {
    red_ink_reversal_form.value.purchase_receipt_details_id = row.id
    red_ink_reversal_form.value.max_number = row.max_red_ink_receipt_number
    red_ink_reversal_form.value.number = row.max_red_ink_receipt_number
  }
}

const red_ink_reversal_form = ref({
  id: '',
  amount: '',
  max_amount: '',
  number: '',
  max_number: '',
  type: 0,
  payments_id: '',
  purchase_receipt_details_id: ''
})

const handleRedInkReversal = () => {
  ElMessageBox.confirm('确定红冲吗?请确定数据无误后谨慎操作', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const params: any = {
      id: red_ink_reversal_form.value.id,
      type: red_ink_reversal_form.value.type
    }
    if (red_ink_reversal_form.value.type == 1) {
      params.amount = red_ink_reversal_form.value.amount
      params.payments_id = red_ink_reversal_form.value.payments_id
    } else {
      params.number = red_ink_reversal_form.value.number
      params.purchase_receipt_details_id = red_ink_reversal_form.value.purchase_receipt_details_id
    }
    redInkReversalApi(params).then((res) => {
      if (res.code == 0) {
        ElMessage.success(t('common.operateSucMsg'))
        red_ink_reversalDialogVisible.value = false
        // 通知父组件刷新数据
        emit('refreshData')
      } else {
        ElMessage.error(t('common.operateFailMsg'))
      }
    })
  })
}

const categoryList = ref([])
const brandList = ref([])

const getCategoryList = async () => {
  const res = await getCategoryListApi({})
  if (res) {
    categoryList.value = res.data.list
  }
}

const getBrandList = async () => {
  const res = await getBrandListApi({})
  if (res) {
    brandList.value = res.data.list
  }
}

getCategoryList()
getBrandList()

const operatorList = ref([])

const getOperatorList = async () => {
  const res = await getSelectListApi({})
  if (res) {
    operatorList.value = res.data.list
  }
}
getOperatorList()

onMounted(async () => {})

const supplierList = ref([])

const getSupplierList = async () => {
  const res = await getSupplierListApi({})
  if (res) {
    supplierList.value = res.data.list
  }
}

getSupplierList()

const purchasePreViewId = 'purchasePreView'
const purchasePreViewIdStore = preViewDialogStore(purchasePreViewId)

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const rules: FormRules = reactive({})

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const purchaseFieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化

const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('product.id'),
    type: 'index',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cname',
    label: t('product.cname'),
    search: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sku',
    label: t('product.sku'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'unit_value',
    label: t('product.unit'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'code',
    label: t('product.code'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'hashrate',
    label: t('product.hashrate'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'category',
    label: t('product.category'),
    search: {
      component: 'Select',
      componentProps: {
        options: categoryList
      }
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.category_value
        }
      }
    }
  },
  {
    field: 'brand',
    label: t('product.brand'),
    search: {
      component: 'Select',
      componentProps: {
        options: brandList
      }
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.brand_value
        }
      }
    }
  }
])
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    purchaseFieldEnum.value = res.data

    const { crudSchemas } = useSchema(
      undefined,
      supplierList,
      purchaseFieldEnum.value,
      tableDialogStoreID,
      tableDialogCurdSchema,
      operatorList,
      props.examine,
      props.detail,
      setValues,
      getFormData
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.purchase_goods.length == 0) {
      ElMessage.error('请选择商品!')
      return false
    }
    formData.purchase_goods.forEach((item) => {
      if (item.unit_price == 0) {
        ElMessage.error('采购商品单价 不能为空!')
        return false
      }
    })
    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    // 排除product_total_amount，避免覆盖动态计算的值
    const { product_total_amount, ...rest } = currentRow
    payments_data_list.value = rest.payments
    purchase_receipt_details_list.value = rest.purchase_receipt_details
    is_show_red_ink_payments.value = rest.is_show_red_ink_payments
    is_show_red_ink_receipt.value = rest.is_show_red_ink_receipt
    red_ink_reversal_form.value.max_amount = rest.max_red_ink_payments_amount
    red_ink_reversal_form.value.id = rest.id
    setValues(rest)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Dialog
    v-model="purchasePreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="purchasePreViewIdStore.src" alt="Preview Image" />
  </Dialog>
  <!--  选择商品弹窗-->
  <TableDialog
    :getListApi="getListApi"
    :limit="tableDialogSelectedLimit"
    :tableDialogStoreID="tableDialogStoreID"
    :itemTitleName="itemTitleName"
  />
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
  <!--  付款明细-->
  <div
    class="flex flex-col lg:flex-row lg:gap-4"
    v-if="props.detail && payments_data_list.length > 0"
  >
    <div class="lg:pt-0 mb-2 lg:mb-0">
      <el-text class="text-lg font-medium whitespace-nowrap">付款明细</el-text>
    </div>
    <div class="flex-1 overflow-x-auto">
      <Table :columns="payments_columns" :data="payments_data_list" />
    </div>
  </div>
  <br />
  <!--  入库明细-->
  <div
    class="flex flex-col lg:flex-row lg:gap-4"
    v-if="props.detail && purchase_receipt_details_list.length > 0"
  >
    <div class="lg:pt-0 mb-2 lg:mb-0">
      <el-text class="text-lg font-medium whitespace-nowrap">入库明细</el-text>
    </div>
    <div class="flex-1 overflow-x-auto">
      <Table :columns="purchase_receipt_details_columns" :data="purchase_receipt_details_list" />
    </div>
  </div>

  <!-- 红冲 -->
  <el-dialog
    v-model="red_ink_reversalDialogVisible"
    :title="t('purchase.red_ink_reversal.title')"
    width="26vw"
  >
    <el-form :model="red_ink_reversal_form" label-width="100px">
      <el-form-item
        :label="t('purchase.red_ink_reversal.amount')"
        v-show="red_ink_reversal_form.type == 1"
      >
        <el-input
          v-model="red_ink_reversal_form.amount"
          :placeholder="'请输入' + t('purchase.red_ink_reversal.amount')"
          style="width: 100%"
        />
        <span class="text-red-500 ml-2 text-xs"
          >{{ t('purchase.red_ink_reversal.max_amount') }}:
          {{ red_ink_reversal_form.max_amount }}</span
        >
      </el-form-item>
      <el-form-item
        :label="t('purchase.red_ink_reversal.number')"
        v-show="red_ink_reversal_form.type == 2"
      >
        <el-input
          v-model="red_ink_reversal_form.number"
          :placeholder="'请输入' + t('purchase.red_ink_reversal.number')"
          style="width: 100%"
        />
        <span class="text-red-500 ml-2 text-xs"
          >{{ t('purchase.red_ink_reversal.max_number') }}:
          {{ red_ink_reversal_form.max_number }}</span
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <BaseButton @click="red_ink_reversalDialogVisible = false">取消</BaseButton>
      <BaseButton type="primary" @click="handleRedInkReversal">确认</BaseButton>
    </template>
  </el-dialog>
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
